package com.cngphone.AnFetion.Fetion.SIPC;

import java.util.ArrayList;

import org.w3c.dom.DOMException;

import com.cngphone.AnFetion.FetionSIPC;
import com.cngphone.AnFetion.FetionUri;
import com.cngphone.AnFetion.Settings;
import com.cngphone.AnFetion.Fetion.TcpSendAndReceive;
import com.cngphone.AnFetion.tools.StrUtil;

public class SetPresence extends SIPCBase {
    private FetionUri fetionid;
    private int newstatus;

    private FetionSIPC sipc;

    public SetPresence(SerialManager serialManager, TcpSendAndReceive connection, FetionUri fetionid,
            int status) {
        super(serialManager, connection);
        this.fetionid = fetionid;
        this.newstatus = status;
    }

    @Override
    public boolean execute() {
        ArrayList<FetionSIPC.HeaderPair> headers = new ArrayList<FetionSIPC.HeaderPair>();
        headers.add(new FetionSIPC.HeaderPair("F", this.fetionid.getId()));
        headers.add(new FetionSIPC.HeaderPair("I", serialManager.getISerial() + " "));
        headers.add(new FetionSIPC.HeaderPair("Q", serialManager.getQSerial() + " S"));
        headers.add(new FetionSIPC.HeaderPair("N", "SetPresence"));

        StringBuilder body = new StringBuilder();
        // TODO 如果是隐身，直接设置成-1，不过桌面版本不是这么处理的，是设置成0，然后PGSetPresence
        if (newstatus == Settings.STATUS_HIDDEN) newstatus = Settings.STATUS_OFFLINE;
        body.append("<args><presence><basic value=\"").append(newstatus).append("\" /></presence></args>");
        headers.add(new FetionSIPC.HeaderPair("L", StrUtil.getLength(body)));

        sipc = new FetionSIPC(SIPC_COMMON_HEADER, headers, body.toString());
        if (this.SendAndReceiveResponse(sipc)) {
            try {
                if (sipc.response.getResponseCmdLine().code.equals(SIPC_RESPONSE_CODE_OK)) {
                    // System.out.println("return true");
                    return true;
                }
            } catch (NumberFormatException e) {
                this.onSetText(e.getMessage());
                e.printStackTrace();
            } catch (DOMException e) {
                this.onSetText(e.getMessage());
                e.printStackTrace();
            } catch (Exception e) {
                this.onSetText(e.getMessage());
                e.printStackTrace();
            }
        }
        return false;
    }

}
